//
//  APIBatchRequestManger.m
//  YYYNetWorkDemo
//
//  Created by yyy on 2016/12/8.
//  Copyright © 2016年 yyy. All rights reserved.
//

#import "APIBatchRequestManger.h"
#import "APIBaseManager.h"

@interface APIBatchRequestManger () <APIManagerApiCallBackDelegate>

@property (nonatomic, assign) NSUInteger finishedCount;

@end

@implementation APIBatchRequestManger

- (instancetype)initWithRequestArray:(NSArray<APIBaseManager *> *)requestArray {
    self = [super init];
    if (self) {
        _requestArray = [requestArray copy];
        _finishedCount = 0;
        for (APIBaseManager *req in _requestArray) {
            if (![req isKindOfClass:[APIBaseManager class]]) {
#ifdef DEBUG
                NSLog(@"Error, request item must be APIBaseManager instance.");
#endif
                return nil;
            }
        }
    }
    return self;
}

- (void)start {
    if (_finishedCount > 0) {
#ifdef DEBUG
        NSLog(@"Error! Batch request has already started.");
#endif
        return;
    }
    _failedRequest = nil;
    for (APIBaseManager *request in _requestArray) {
        request.delegate = self;
        [request loadData];
    }
}

- (void)stop {
    _delegate = nil;
    [self clearRequest];
}

- (void)startWithCompletionBlock:(void (^)(BOOL, APIBatchRequestManger *_Nonnull))complete {
    self.completionBlock = complete;
    [self start];
}

- (void)dealloc {
    [self clearRequest];
}

#pragma mark - Network Request Delegate

- (void)managerCallAPIDidComplete:(APIBaseManager *)manager success:(BOOL)success {
    if (success) {
        _finishedCount++;
        if (_finishedCount == _requestArray.count) {
            if (self.delegate) {
                if ([self.delegate respondsToSelector:@selector(batchRequestSuccess:)]) {
                    [self.delegate batchRequestSuccess:self];
                }
                if ([self.delegate respondsToSelector:@selector(batchRequestDidComplete:success:)]) {
                    [self.delegate batchRequestDidComplete:self success:YES];
                }
            }
            if (_completionBlock) {
                _completionBlock(YES, self);
            }
        }
    } else {
        _failedRequest = manager;
        if (self.delegate) {
            if ([self.delegate respondsToSelector:@selector(batchRequest:didFailedWithManager:)]) {
                BOOL needContinue = [self.delegate batchRequest:self didFailedWithManager:manager];
                if (needContinue) {
                    //需要继续的话，直接将该次请求当成成功处理了。
                    [self managerCallAPIDidComplete:manager success:YES];
                    return;
                }
            }
            
            if ([self.delegate respondsToSelector:@selector(batchRequestFailed:)]) {
                [self.delegate batchRequestFailed:self];
            }
            if ([self.delegate respondsToSelector:@selector(batchRequestDidComplete:success:)]) {
                [self.delegate batchRequestDidComplete:self success:NO];
            }
        }
        if (_completionBlock) {
            _completionBlock(NO, self);
        }
        [self stop];
    }
}

- (void)clearRequest {
    self.completionBlock = nil;
    for (APIBaseManager *req in _requestArray) {
        [req cancelAllRequestsAndIgonerCallBack];
    }
}

@end
